///*
// * To change this license header, choose License Headers in Project Properties.
// * To change this template file, choose Tools | Templates
// * and open the template in the editor.
// */
//package com.sinosoft.gateway.filter;
//
//import com.alibaba.fastjson.JSONObject;
//import com.sinosoft.feign.oauth2.OauthFeign;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.cloud.gateway.filter.GatewayFilterChain;
//import org.springframework.cloud.gateway.filter.GlobalFilter;
//import org.springframework.core.Ordered;
//import org.springframework.core.io.buffer.DataBuffer;
//import org.springframework.http.HttpStatus;
//import org.springframework.util.AntPathMatcher;
//import org.springframework.web.server.ServerWebExchange;
//import reactor.core.publisher.Flux;
//import reactor.core.publisher.Mono;
//
//import java.nio.charset.StandardCharsets;
//import java.util.List;
//import java.util.Map;
//import org.springframework.stereotype.Component;
//
///**
// *
// * @author root
// */
//@Component
//public class Gfilter implements GlobalFilter, Ordered {
//
//    public Logger logger = LoggerFactory.getLogger(getClass());
//    @Autowired
//    OauthFeign oauthfeign;
//    @Autowired
//    GProperties routeproperties;
//    AntPathMatcher ant = new AntPathMatcher();
//
//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//
//        logger.info("Incomming Request   @@" + exchange.getRequest().getRemoteAddress().getAddress() + "   @@" + exchange.getRequest().getURI());
//
//        List<String> token = exchange.getRequest().getQueryParams().get("access_token");
//        //如果没带token, 返回no token provided
//        if (token == null || token.isEmpty()) {
//            logger.error("No Token !!" + exchange.getRequest().getRemoteAddress().getAddress() + "   !!" + exchange.getRequest().getURI());
//            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//            byte[] bytes = "401 no token provided".getBytes(StandardCharsets.UTF_8);
//            DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
//            return exchange.getResponse().writeWith(Flux.just(buffer));
//
//        }
//
////        RestTemplate rest = new RestTemplate();
//        JSONObject user = new JSONObject();
////        String url = "http://localhost:8043/user?access_token=" + token.get(0);
//        try {
////            user = rest.getForObject(url, JSONObject.class);
//            user = oauthfeign.oauth2user(token.get(0));
//            logger.info("uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu    " + user);
//            //如果localhost:8043/user调不通, 返回invalid token
//            if (user.containsKey("code") && user.containsKey("msg")) {
//                logger.error("Invalid Token !!" + exchange.getRequest().getRemoteAddress().getAddress() + "   !!" + exchange.getRequest().getURI());
//                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//                byte[] bytes = "401 invalid token".getBytes(StandardCharsets.UTF_8);
//                DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
//                return exchange.getResponse().writeWith(Flux.just(buffer));
//            }
//
//            //如果localhost:8043/user调通了，　看看那些接口对这个token开放
//            if (user.containsKey("details") && user.containsKey("oauth2Request")) {
//                //如果请求的接口在token授权范围内，放行
//                if (checkUri(exchange.getRequest().getURI().getPath(), user)) {
//                    logger.info("Access Granted   @@" + exchange.getRequest().getRemoteAddress().getAddress() + "   @@" + exchange.getRequest().getURI());
//                    return chain.filter(exchange);
//                } else {
//                    //如果请求的接口不在token授权范围内，返回权限不够
//                    logger.error("Token Not Enough !!" + exchange.getRequest().getRemoteAddress().getAddress() + "   !!" + exchange.getRequest().getURI());
//                    exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//                    byte[] bytes = "401 sorry your token cannot perform this action".getBytes(StandardCharsets.UTF_8);
//                    DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
//                    return exchange.getResponse().writeWith(Flux.just(buffer));
//                }
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            logger.error("Authorization Server Down!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
//
//        }
//        logger.error("Unexpected Return From Authorization Server!!!!!!!!!!!!!!!");
//        return null;
//    }
//
//    public boolean checkUri(String requestUri, JSONObject user) {
//        logger.info("checkUri");
//        List<String> resourceIds = user.getJSONObject("oauth2Request").getJSONArray("resourceIds").toJavaList(String.class);
//        for (Map<String, String> map : routeproperties.getRoutes()) {
//            if (ant.match(map.get("predicates.0").replace("Path=", ""), requestUri)) {
//                if (resourceIds.contains(map.get("id"))) {
//                    return true;
//                }
//            }
//        }
//        return false;
//    }
//
//    @Override
//    public int getOrder() {
//        return 1;
//    }
//
//}
